//各种通用工具类
const { md5 } = require("./utils.crypto");
const utilsTools = {
    //生成永不重复的id
    uuid: () => {
        return md5((new Date()).getTime() + '-' + Math.random().toString().substr(2, 5)
        ).toString()
    },
    //去除对象和数组中所有空字符 ('') 和 null 值的字段
    cleanObject: (data) => {
        if (Array.isArray(data)) {
            // 处理数组，递归清理每个元素，并过滤掉空对象或数组
            return data
                .map(item => utilsTools.cleanObject(item))
                .filter(item => !(typeof item === 'object' && Object.keys(item).length === 0 && Object.getOwnPropertySymbols(item).length === 0));
        } else if (typeof data === 'object' && data !== null) {
            // 获取对象的所有属性，包括 Symbol
            const allKeys = [...Object.keys(data), ...Object.getOwnPropertySymbols(data)];

            return allKeys.reduce((acc, key) => {
                const cleanedValue = utilsTools.cleanObject(data[key]);
                // 过滤掉 null 和 空字符串的值，以及空对象和空数组
                if (cleanedValue !== '' && cleanedValue !== null &&
                    (typeof cleanedValue !== 'object' || Object.keys(cleanedValue).length > 0 || Object.getOwnPropertySymbols(cleanedValue).length > 0)) {
                    acc[key] = cleanedValue;
                }
                return acc;
            }, {});
        }
        // 对于非对象类型，直接返回原值
        return data;
    },

    // 获取固定长度的随机字符
    randomStr: (len = 32) => {
        let t = "QWERTYUOPASDFGHJKLZXCVBNMqwertyuipasdfghjkzxcvbnm23456789";
        let val = "";
        for (let i = 0; i < len; i++) {
            val += t.charAt(Math.floor(Math.random() * t.length));
        }
        return val;
    },
    // 获取固定长度的随机数字
    randomNum: (len = 6) => {
        let t = "1234567890";
        let val = "";
        for (let i = 0; i < len; i++) {
            val += t.charAt(Math.floor(Math.random() * t.length));
        }
        return val;
    },
    // 下划转驼峰
    lineToHump: (data) => {
        if (typeof data !== "object" || !data) return data;
        // 选序列化数据
        data = JSON.parse(JSON.stringify(data));
        if (Array.isArray(data)) {
            return data.map(item => utilsTools.lineToHump(item))
        }
        const newData = {}
        for (let key in data) {
            let newKey = key.replace(/_([a-z])/g, (p, m) => m.toUpperCase())
            newData[newKey] = utilsTools.lineToHump(data[key])
        }
        return newData
    },
    // 驼峰转下划线
    humpToLine: (data) => {
        if (typeof data !== "object" || !data) return data;
        // 选序列化数据
        data = JSON.parse(JSON.stringify(data));
        if (Array.isArray(data)) {
            return data.map(item => utilsTools.humpToLine(item))
        }
        const newData = {}
        for (let key in data) {
            let newKey = key.replace(/[A-Z]/g, (p, m) => "_" + p.toLowerCase())
            newData[newKey] = utilsTools.humpToLine(data[key])
        }
        return newData
    },
}
module.exports = utilsTools
